import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Myorder from '@/views/myorder'
import Pay from '@/views/pay'
import Prodetail from '@/views/prodetail'
import Search from '@/views/search'
import Home from '@/views/layout/home'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'
import Category from '@/views/layout/category'
import store from '@/store'
import list from '@/views/search/list'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home', // 添加重定向到home，默认状态
      children: [
        { path: '/home', component: Home },
        { path: '/cart', component: Cart },
        { path: '/user', component: User },
        { path: '/category', component: Category }
      ]
    },
    { path: '/myorder', component: Myorder },
    { path: '/pay', component: Pay },
    { path: '/prodetail/:id', component: Prodetail }, // 动态路由传参，确认将来是哪个商品
    { path: '/search', component: Search },
    { path: '/searchList', component: list }
  ]
})

// 所有的路由在真正被访问之前（渲染解析对应组件页面），都回先经过全局前置守卫
// 只有全局前置守卫放行了，才回到达对应的页面
// 添加全局路由守卫
// to 代表要去的路径
// from 代表从哪个路径跳转过来的
// next 代表放行的路径
// （1）.next() 直接放行，放行到to的路径
// （2）. next（'/路径'）进行拦截，拦截到next里面配置的路径
// 定义一个数组，专门存放有权限才可以访问的路由
const authUrl = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 如果不是有权限的页面就放行
  if (!authUrl.includes(to.path)) {
    next()
    return
  }
  // const token = store.state.user.UserInfo.token
  // 如果是要有权限的页面，则判断是否有token
  const token = store.getters.token
  // 如果有就跳转
  if (token) {
    next()
  } else { // 没有则跳转到login页面
    next('/login')
  }
})
export default router
